﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Threading;

using CE.User;
using CE.Global;
using CE.AreaCountry;
using CE.TravelInsurance;
using CE.Company;
using CE.Database;
using CE.Wego;

public partial class travel_flights_flights_search_new : System.Web.UI.Page
{
    WegoFlights myflight = new WegoFlights();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            if (Request.IsSecureConnection)
            {
                string redirectUrl = Request.Url.ToString().Replace("https:", "http:");

                Response.Redirect(redirectUrl);
            }

            Session[General.TAId] = null;
            Session["wegosearchparams"] = null;
            General.ClearAllSession(this.Page, "TA");
            Session[General.ViewedDetailsId] = LogUserViewedHistory().ToString();

            //if (Cache["flights" + Session[General.ViewedDetailsId].ToString()] != null)
            //    Cache.Remove("flights" + Session[General.ViewedDetailsId].ToString());

            if (Session["flightsid"] != null)
            {
                if (Cache["flights" + Session["flightsid"].ToString()] != null)
                    Cache.Remove("flights" + Session["flightsid"].ToString());
            }


        }
    }

    protected void btnSearch_Click(object sender, EventArgs e)
    {
        if (CheckValidation())
        {
            if (Page.IsValid)
            {
                if (Session[General.ViewedDetailsId] == null || Session[General.ViewedDetailsId].ToString() == "")
                {
                    //this.Page_Load(e, null);
                    Session[General.ViewedDetailsId] = LogUserViewedHistory().ToString();
                }

                if (Session[General.TAId] != null)
                    Cache.Remove("TAResultsQuotes" + Session[General.TAId].ToString());

                if (Session["flightsid"] != null)
                {
                    if (Cache["flights" + Session["flightsid"].ToString()] != null)
                        Cache.Remove("flights" + Session["flightsid"].ToString());
                }

                //if (Cache["flights" + Session[General.ViewedDetailsId].ToString()] != null)
                //    Cache.Remove("flights" + Session[General.ViewedDetailsId].ToString());


                Int64 countryid = 0;
                Int64 areaid = 0;
                string coveragelevel = "S";
                Int32 duration = 0;
                DateTime startdate = new DateTime(1900, 1, 1);
                DateTime enddate = new DateTime(1900, 1, 1);
                Int32 childage = 0;
                Int32 adultage1 = 0;
                Int32 adultage2 = 0;
                Int32 adultage3 = 0;
                Int32 adultage4 = 0;

                Int32 noofadults = 0;
                DateTime dobadult1 = CE.Global.General.GetUTCDateTime();
                DateTime dobadult2 = CE.Global.General.GetUTCDateTime();
                DateTime dobadult3 = CE.Global.General.GetUTCDateTime();
                DateTime dobadult4 = CE.Global.General.GetUTCDateTime();
                Int32 noofchilds = 0;
                DateTime dobchild1 = CE.Global.General.GetUTCDateTime();
                DateTime dobchild2 = CE.Global.General.GetUTCDateTime();
                DateTime dobchild3 = CE.Global.General.GetUTCDateTime();
                DateTime dobchild4 = CE.Global.General.GetUTCDateTime();
                DateTime dobchild5 = CE.Global.General.GetUTCDateTime();
                DateTime dobchild6 = CE.Global.General.GetUTCDateTime();

                //Default Scenario

                string locfrom = Request.Form["wg_from"].ToString().Trim();
                string locto = Request.Form["wg_to"].ToString().Trim();
                string outbounddate = Request.Form["wg_outbound_date"].ToString().Trim();
                string inbounddate = "";

                if (Request.Form["wg_inbound_date"] != null)
                {
                    if (Request.Form["wg_inbound_date"].ToString().Trim() != "")
                        inbounddate = Request.Form["wg_inbound_date"].ToString().Trim();
                }
                else
                {
                    inbounddate = outbounddate;
                }
                string noofadult = Request.Form["ctl00$ContentPlaceHolder1$wg_adult"].ToString().Trim();
                string noofchild = Request.Form["wg_children"].ToString().Trim();
                string cabinclass = "Economy"; //Default
                string triptype = Request.Form["wg_trip_type"].ToString().Trim();
                string locfromname = Request.Form["wg_origin"].ToString().Trim();
                string loctoname = Request.Form["wg_destination"].ToString().Trim();

                if (triptype == "true")
                {
                    triptype = "roundTrip";
                }
                else
                {
                    triptype = "oneWay";
                }

                string[] outbounddateformatted = outbounddate.Split('/');
                string departuredate = outbounddateformatted[2] + "-" + outbounddateformatted[1] + "-" + outbounddateformatted[0];

                string[] inbounddateformatted = new string[3];
                string arrivaldate = "";

                if (triptype == "roundTrip")
                {
                    inbounddateformatted = inbounddate.Split('/');
                    arrivaldate = inbounddateformatted[2] + "-" + inbounddateformatted[1] + "-" + inbounddateformatted[0];
                }
                else
                {
                    outbounddateformatted = outbounddate.Split('/');
                    arrivaldate = outbounddateformatted[2] + "-" + outbounddateformatted[1] + "-" + outbounddateformatted[0];
                }


                DateTime dateOutbound = Convert.ToDateTime(departuredate);
                DateTime dateInbound = Convert.ToDateTime(arrivaldate);

                countryid = GetCountryIdOfAirport(locto); //Convert.ToInt64(ddlS1DestCountry.SelectedValue.ToString());
                coveragelevel = "S";
                duration = ComputeDuration(dateOutbound, dateInbound);
                startdate = dateOutbound;
                enddate = dateInbound;
                adultage1 = 25; //default
                dobadult1 = CE.Global.General.GetUTCDateTime().AddYears(-25);//default
                noofadults = int.Parse(noofadult);
                noofchilds = int.Parse(noofchild);




                TAApplicantSearch _taapplicantsearch = new TAApplicantSearch();
                TAApplicantSearchDB _taapplicantsearchdb = new TAApplicantSearchDB();


                if (Session[General.TAId] == null)
                {
                    _taapplicantsearch.TAAppSeaId = 0;
                }
                else
                {
                    _taapplicantsearch.TAAppSeaId = Convert.ToInt64(Session[General.TAId].ToString());
                }

                if (Session[General.UserId] == null)
                {
                    //_taapplicantsearch.RefCEUserId = CheckAndCreateAndSendMailToUser();
                }
                else
                {
                    _taapplicantsearch.RefCEUserId = Convert.ToInt64(Session[General.UserId].ToString());
                }

                _taapplicantsearch.Name = ""; // txtOwnerName.Text.Trim();
                _taapplicantsearch.EmailAddress = ""; // txtOwnerEmailAddress.Text.Trim();
                _taapplicantsearch.MobileNum = ""; // txtOwnerPhoneNo.GetPhoneNo().ToString();
                _taapplicantsearch.PlanType = "IND"; //Individual Default - ddlPolicyType.SelectedValue.ToString();
                _taapplicantsearch.TripType = "S"; //Single Default - ddlTripType.SelectedValue.ToString();
                _taapplicantsearch.CountryID = countryid;
                _taapplicantsearch.AreaID = areaid;
                _taapplicantsearch.CoverageLevel = coveragelevel;
                _taapplicantsearch.Duration = duration;
                _taapplicantsearch.StartDate = startdate;
                _taapplicantsearch.EndDate = enddate;
                _taapplicantsearch.ChildAge = childage;
                _taapplicantsearch.AdultAge = adultage1;
                _taapplicantsearch.NoOfTravellers = noofadults + noofchilds;
                _taapplicantsearch.TotalPremium = 0;

                _taapplicantsearch.NoofAdults = noofadults;
                _taapplicantsearch.DOBAdult1 = dobadult1;
                _taapplicantsearch.DOBAdult2 = dobadult2;
                _taapplicantsearch.DOBAdult3 = dobadult3;
                _taapplicantsearch.DOBAdult4 = dobadult4;
                _taapplicantsearch.NoofChilds = noofchilds;
                _taapplicantsearch.DOBChild1 = dobchild1;
                _taapplicantsearch.DOBChild2 = dobchild2;
                _taapplicantsearch.DOBChild3 = dobchild3;
                _taapplicantsearch.DOBChild4 = dobchild4;
                _taapplicantsearch.DOBChild5 = dobchild5;
                _taapplicantsearch.DOBChild6 = dobchild6;

                _taapplicantsearch.ViewedDetailId = Convert.ToInt64(Session[General.ViewedDetailsId].ToString());

                _taapplicantsearch.Info1 = "0";
                Int64 _result = _taapplicantsearchdb.Insert(_taapplicantsearch);

                if (_result > 0)
                {


                    Session["TripType"] = "S"; // ddlTripType.Text;
                    Session[General.TAId] = _result.ToString();

                    if (Session[General.UserId] == null)
                    {
                        Session[General.TAPersonnelId] = _taapplicantsearch.RefCEUserId.ToString();
                        Session[General.TAUserName] = ""; // txtFullName.Text;
                        Session[General.TAPhoneNo] = ""; // txtMobileNo.GetPhoneNo().ToString();
                        Session[General.TAEmail] = ""; // txtEmail.Text;
                    }


                    //default for now
                    int usagecount = 1;
                    int maxcount = 100;
                    string startTimeBucket = "";
                    string endTimeBucket = "";

                    // 5 tries
                    int noOfAttempts = 5;


                    //for (int i = 0; i < noOfAttempts; i++)
                    //{
                    //    DataSet _dsUsage = myflight.CheckAPIUsage();
                    //    if (_dsUsage != null)
                    //    {
                    //        if (_dsUsage.Tables["errors"] == null)
                    //        {
                    //            if (_dsUsage.Tables[0].Rows.Count > 0)
                    //            {
                    //                usagecount = int.Parse(_dsUsage.Tables["usageCount"].Rows[0].ItemArray[0].ToString());
                    //                maxcount = int.Parse(_dsUsage.Tables["maxCount"].Rows[0].ItemArray[0].ToString());
                    //                startTimeBucket = _dsUsage.Tables[0].Rows[0]["startTimeBucket"].ToString();
                    //                endTimeBucket = _dsUsage.Tables[0].Rows[0]["endTimeBucket"].ToString();

                    //                break;
                    //            }
                    //        }
                    //    }
                    //}

                    string instanceid = "";
                    string usage = "";
                    //if (usagecount < maxcount)
                    //{
                    //    lblMessage.Visible = false;
                    //    DataSet _dsInstance = new DataSet();

                    //    for (int i = 0; i < noOfAttempts; i++)
                    //    {
                    //        _dsInstance = myflight.SearchFlight(locfrom, locto, triptype, cabinclass, arrivaldate, departuredate, noofadult, noofchild);

                    //        if (_dsInstance != null)
                    //        {
                    //            lblMessage.Visible = false;

                    //            if (_dsInstance.Tables["errors"] == null)
                    //            {
                    //                instanceid = _dsInstance.Tables[0].Rows[0]["instanceid"].ToString();
                    //                usage = _dsInstance.Tables[0].Rows[0]["usage"].ToString();

                    //                string[] sessionparams = new string[11];
                    //                sessionparams[0] = locfrom;
                    //                sessionparams[1] = locto;
                    //                //sessionparams[2] = outbounddate;
                    //                //sessionparams[3] = inbounddate;
                    //                sessionparams[2] = departuredate;
                    //                sessionparams[3] = arrivaldate;
                    //                sessionparams[4] = noofadult;
                    //                sessionparams[5] = triptype;
                    //                sessionparams[6] = locfromname;
                    //                sessionparams[7] = loctoname;
                    //                sessionparams[8] = outbounddate;
                    //                sessionparams[9] = inbounddate;
                    //                sessionparams[10] = noofchild;

                    //                Session["wegosearchparams"] = sessionparams;

                    //                if (instanceid != "")
                    //                {
                    //                    //System.Threading.Thread.Sleep(5000);

                    //                    //break;
                    //                    bool isRoundtrip = false;
                    //                    if (triptype == "roundTrip")
                    //                        isRoundtrip = true;

                    //                    //bool isdone = GetFlights(instanceid, isRoundtrip, departuredate, arrivaldate, locfrom, locto);

                    //                    //if (isdone)
                    //                    //{
                    //                    //    Response.Redirect("results-new.aspx?insid=" + instanceid);
                    //                    //    break;
                    //                    //}

                    //                    Response.Redirect("results.aspx?insid=" + instanceid);
                    //                    //lblMessage.Visible = true;
                    //                    //lblMessage.Text = "Cool!";
                    //                }
                    //                else
                    //                {
                    //                    this.Page_Load(this, null);
                    //                }


                    //            }
                    //        }
                    //    }

                    //    if (_dsInstance == null)
                    //    {
                    //        lblMessage.Visible = true;
                    //        lblMessage.Text = "*Please try again.";

                    //    }
                    //}
                    //else
                    //{
                    //    //Max request reached. Pls. try again after 5 minutes
                    //    lblMessage.Visible = true;
                    //    lblMessage.Text = "*Maximum request reached. Please try again after 5 minutes.";
                    //}


                    string[] sessionparams = new string[11];
                    sessionparams[0] = locfrom;
                    sessionparams[1] = locto;
                    //sessionparams[2] = outbounddate;
                    //sessionparams[3] = inbounddate;
                    sessionparams[2] = departuredate;
                    sessionparams[3] = arrivaldate;
                    sessionparams[4] = noofadult;
                    sessionparams[5] = triptype;
                    sessionparams[6] = locfromname;
                    sessionparams[7] = loctoname;
                    sessionparams[8] = outbounddate;
                    sessionparams[9] = inbounddate;
                    sessionparams[10] = noofchild;

                    Session["wegosearchparams"] = sessionparams;

                    Response.Redirect("results.aspx");
                }

                LogUserViewedHistory();



            } //end page.valid
        }
    }

    private bool CheckValidation()
    {
        string triptype = Request.Form["wg_trip_type"].ToString().Trim();

        if (Request.Form["wg_origin"].ToString().Trim() == "")
        {
            return false;
        }

        if (Request.Form["wg_destination"].ToString().Trim() == "")
        {
            return false;
        }

        if (triptype == "true") //roundtrip
        {
            if (Request.Form["wg_inbound_date"].ToString().Trim() == "")
            {
                return false;
            }
        }


        if (Request.Form["wg_outbound_date"].ToString().Trim() == "")
        {
            return false;
        }


        return true;

    }

    private Int64 LogUserViewedHistory()
    {
        UserViewHistoryDB _userviewdb = new UserViewHistoryDB();
        return _userviewdb.LogViewedHistory("FL", Request, "Travel Flights Search Page.");
    }

    protected void lnkbtnBack_Click(object sender, EventArgs e)
    {

        //start.Enabled = false;
        //UpdateProgress1.Attributes.Add("display", "none");

        //this.Page_Load(this, null);

        if (Session["wegosearchparams"] != null)
            Session.Remove("wegosearchparams");

        if (Session["flightsid"] != null)
            Session.Remove("flightsid");


        Response.Redirect("flights-search.aspx", true);



    }

    private bool GetFlights(string instanceid, bool isRoundtrip, string outbounddate, string inbounddate, string locfrom, string locto)
    {
        bool isdone = false;
        Int64 searchid = 0;
        Int64 userid = 0;

        if (Session[General.UserId] != null)
        {
            userid = Convert.ToInt64(Session[General.UserId].ToString());
        }

        WegoFlightsDB wegodb = new WegoFlightsDB();

        searchid = wegodb.InsertSearch(locfrom, locto, DateTime.Parse(outbounddate), DateTime.Parse(inbounddate), userid);

        if (searchid > 0)
        {
            Session["flightsid"] = searchid.ToString();
            Int64 isClear = wegodb.ClearTables(searchid);

            if (isClear == 1)
            {
                //isdone = true;
                isdone = myflight.GetFlightResults(instanceid, isRoundtrip, outbounddate, inbounddate, searchid.ToString(), 1, 0, CE.Global.General.GetUTCDateTime());
            }
        }


        return isdone;
    }

    private int ComputeDuration(DateTime dtFrom, DateTime dtTo)
    {
        int TripDuration = 0;
        TripDuration = Convert.ToInt32(dtTo.Subtract(dtFrom).TotalDays.ToString());
        TripDuration = TripDuration + 1;

        return TripDuration;
    }

    private string GetAreadIdOfCountry(Int64 CountryId)
    {
        string AreaId = "0";
        AreaCountryInfoDB _areacountrydb = new AreaCountryInfoDB();
        AreaId = _areacountrydb.GetAreaIDByCountryID(CountryId).ToString();

        return AreaId;
    }

    private Int64 GetCountryIdOfAirport(string airportcode)
    {
        Int64 CountryId = 0;
        CountryAirportInfoDB _countryairportdb = new CountryAirportInfoDB();

        DataTable dtCountry = _countryairportdb.GetCountryIdByAirport(airportcode);

        if (dtCountry.Rows.Count > 0)
        {
            CountryId = Int64.Parse(dtCountry.Rows[0]["CountryId"].ToString());
        }

        return CountryId;
    }

    private void ClearSession()
    {
        Session[General.TAId] = null;
        Session[General.TAPhoneNo] = null;
        Session[General.TAEmail] = null;
        Session[General.TAUserName] = null;
        Session[General.TAResultId] = null;
        Session[General.TACustomerAge] = null;
    }
}
